namespace.reg("userManage.fun");
userManage.fun = (function () {
    var initGrid = function (url) {
        var initTableData = function (currentPage, pageSize, parame) {
            if (baseJS.isEmpty(currentPage)) {
                currentPage = 1;
            }
            if (baseJS.isEmpty(pageSize)) {
                pageSize = 10;
            }
            var tableInitParam = {};
            var datas = {currentPage: currentPage, pageSize: pageSize};
            if (!baseJS.isEmpty(parame)) {
                $.extend(datas, parame);
            }
            baseJS.ajaxRequest({
                url:"/backstage/getUserPageList",
                data:datas,
                success:function successCallback(reqData) {
                    tableInitParam = {
                        tableData: reqData.data,
                        total: reqData.number,
                        pageSize: 10,
                        currentPage: 1,
                    };
                },
                error:function errorCallback() {
                    baseJS.layerMsg("ajaxRequest请求出错");
                }
            });
            return tableInitParam;
        }
        var updataStatus = function (switchStatus,item) {
            var msg = baseJS.ajaxRequestSsyncFalse("/backstage/userManage/updateStatus",{
                id:item.id,
                status:switchStatus
            });
            if(msg.status == 1){
                baseJS.layerMsg("更新成功");
                return 1;
            }
        }
        var deleteTableData = function (id, callback) {
            $.ajax({
                url: "/backstage/deleteUser",
                dataType: "json",
                async: false,
                data: {id: id},
                type: "post",
                success: function (reqData) {
                    if (callback != null && typeof(callback) == "function") {
                        callback(reqData);
                    } else {
                        if (reqData.status) {
                            baseJS.layerMsg(reqData.msg);
                        }
                    }
                },
                error: function () {
                    baseJS.layerMsg("删除出错");
                }
            });
        };
        var app = new Vue({
            data:function() {
                var reqIniData = initTableData(1, 10);
                return {
                    item : null,
                    type : "add",
                    total: reqIniData.total,
                    pageSize: reqIniData.pageSize,
                    currentPage: reqIniData.currentPage,
                    selectRow: [],
                    loadedData:function(currentPage, pageSize, parame) {
                        var pageData = initTableData(currentPage, pageSize, parame);
                        this.pageSize = pageData.pageSize;
                        this.total = pageData.total;
                        this.tableData = pageData.tableData;
                    },
                    columns: [
                        {
                            type: 'selection',
                            width: 60,
                            align: 'center'
                        },
                        {
                            title: '用户名',
                            key: 'username'
                        },
                        {
                            title: '最后登录时间',
                            key: 'lastLoginTime'
                        },
                        {
                            title: '邮箱',
                            key: 'email'
                        },
                        {
                            title: '登录ip地址',
                            key: 'ipDddress'
                        },
                        {
                            title: '状态',
                            key: 'status',
                            align: 'center',
                            render: function(h, params) {
                                return h('i-switch', {
                                    props: {
                                        value: params.row.status,
                                        size:'large',
                                        trueValue:1,
                                        falseValue:0

                                    },
                                    on: {
                                        input: function (value) {
                                            if(updataStatus(value,params.row) == 1){
                                                params.row.status = value;
                                            }
                                        }
                                    }
                                },[
                                    h('span',{slot:'open'},'启用'),
                                    h('span',{slot:'close'},'禁用')
                                ])
                            }
                        },
                        {
                            title: '操作',
                            key: 'action',
                            width: 150,
                            align: 'center',
                            render: function(h, params) {
                                return h('div', [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: function(){
                                                app.editFun(params.index,params.row)
                                            }
                                        }
                                    }, '编辑'),
                                    h('Button', {
                                        props: {
                                            type: 'error',
                                            size: 'small'
                                        },
                                        on: {
                                            click: function(){
                                                app.delete(params.index)
                                            }
                                        }
                                    }, '删除')
                                ]);
                            }
                        }
                    ],
                    tableData: reqIniData.tableData
                }
            },
            methods: {
                handleRowChange(selection){
                    this.selectRow = selection;
                },
                onPageSizeChange:function (value) {
                    this.loadedData(1,value);
                },
                delete:function(index) {
                    baseJS.layerOpenAle("确定要删除吗？", "温馨提示", function () {
                        deleteTableData(vueGridApp.tableData[index].id,function callback(reqData) {
                            if( reqData.status ){
                                vueGridApp.tableData.splice(index, 1);
                                if(vueGridApp.tableData.length == 0){
                                    vueGridApp.loadedData(vueGridApp.currentPage - 1, vueGridApp.pageSize);
                                }
                                baseJS.layerMsg(reqData.msg);
                            }
                        });
                    });
                },
                deleteBatch:function(ev) {
                    var vueThis = this;
                    const selectRow = this.selectRow;
                    if (selectRow.length == 0) {
                        baseJS.layerMsg("请选择要删除的数据");
                        return true;
                    } else {
                        baseJS.layerOpenAle("确定要删除吗？", "温馨提示", function () {
                            var itemIds = [];
                            for (var index in selectRow) {
                                itemIds.push(selectRow[index].id);
                            }
                            baseJS.ajaxRequest({
                                url:"/backstage/userManage/deleteBatch",
                                data:{itemIds: itemIds.join(",")},
                                success:function successCallback(data) {
                                    if (!baseJS.isEmpty(data) && data.status == 1) {
                                        baseJS.layerMsg(data.msg, function callback() {
                                            vueThis.loadedData(vueThis.currentPage, vueThis.pageSize);
                                        });
                                    } else {
                                        baseJS.layerMsg("删除失败！");
                                    }
                                },
                                error:function errorCallback() {
                                    baseJS.layerMsg("删除失败！");
                                }
                            });
                        });
                    }
                },
                addButt:function () {
                    var vueThis = this;
                    this.type = "add";
                    baseJS.baseLayerOpen({
                        url:"/backstage/userManage/userAdd"
                        ,title:"新增用户"
                        ,type:2
                        ,width:650
                        ,height:408
                        ,maxmin:false
                        ,successCallbackLayerOpenFun:function (val, indexs) {
                            vueThis.iframeIndex = indexs;
                        }
                    });
                },
                editFun:function (index,row) {
                    var vueThis = this;
                    this.item = row;
                    this.type = "edit";
                    baseJS.baseLayerOpen({
                        url:"/backstage/userManage/userAdd"
                        ,title:"编辑用户"
                        ,type:2
                        ,width:650
                        ,height:408
                        ,maxmin:false
                        ,successCallbackLayerOpenFun:function (val, indexs) {
                            vueThis.iframeIndex = indexs;
                        }
                    });
                },
                pageNext:function (currentPage) {
                    this.loadedData(currentPage, this.pageSize);
                }
            }
        });
        vueGridApp = app;
        app.$mount('#app')
    }
    var initAddForm = function (item) {
        var formApp = new Vue({
            data: function () {
                const validateUsername = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error( '用户名不能为空'));
                    } else {
                        var uPattern = /^([a-zA-Z0-9])|([\u4e00-\u9fa5])$/;
                        if (this.formValidate.username !== '' && uPattern.test(value)) {
                            if(this.formValidate.username.length > 10){
                                callback(new Error( '用户名长度不能超过10个字符'));
                            }else{
                                callback();
                            }
                        }else{
                            callback(new Error( '只能包含字母，数字，汉字'));
                        }
                    }
                };
                const validatePass = (rule, value, callback) =>{
                    if (value === '') {
                        callback(new Error( '密码不能为空'));
                    } else {
                        var pattern = /^(?=.*[0-9])((?=.*[a-z])[0-9a-z]+|(?=.*[!@#$%^&*])[\da-zA-Z~!@#$%^&*]+)$/ig;
                        if (value !== '') {
                            if(!pattern.test(value)){
                                callback(new Error( '密码由字母，数字或特殊符号组成'));
                            }else if(value.length < 6 || value.length > 16){
                                callback(new Error( '密码长度为6到16之间'));
                            }else{
                                this.$refs.formValidate.validateField('passwordCheck');
                                callback();
                            }
                        }
                    }
                };
                const validatePassCheck = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请确认密码'));
                    } else if (value !== this.formValidate.password) {
                        callback(new Error('密码不一致!'));
                    } else {
                        callback();
                    }
                };
                var formValidateParamet = {
                    loading: false,
                    status:'0',
                    username: '',
                    password: '',
                    passwordCheck: '',
                    disabledReset: false,
                    roleSelect: []
                }
                if(item != null){
                    $.extend(formValidateParamet, item);
                    formValidateParamet.status = formValidateParamet.status.toString();
                    formValidateParamet.passwordCheck = 'a123654**';
                    formValidateParamet.password = 'a123654**';
                    var roleList = item.roleList;
                    for(var index in roleList){
                        formValidateParamet.roleSelect.push(roleList[index].roleId);
                    }
                }

                return {
                    formValidate:formValidateParamet,
                    ruleValidate: {
                        username: [
                            { required: true, validator: validateUsername, trigger: 'blur' }
                        ],
                        password: [
                            { required: true, validator: validatePass, trigger: 'blur' },
                            { type: 'string', min: 6, message: '密码至少六位数', trigger: 'blur' }
                        ],
                        passwordCheck: [
                            { required: true, validator: validatePassCheck, trigger: 'blur' },
                            { type: 'string', min: 6, message: '密码至少六位数', trigger: 'blur' }
                        ],
                        roleArray:getRoleList()
                    }
                }
            },
            methods: {
                onSubmit : function(name){
                    this.$refs[name].validate((valid) => {
                        if (valid) {
                            this.formValidate.loading = true;
                            this.formValidate.disabledReset = true;
                            var datas = {
                                status:this.formValidate.status,
                                roleIds:this.formValidate.roleSelect,
                                username:this.formValidate.username,
                                password: (parent.vueGridApp.type == "edit" && this.formValidate.password == "a123654**") ? item.password : md5(this.formValidate.password)
                            };
                            var url ="/backstage/userManage/addUser";
                            var msg = "新增";
                            if (parent.vueGridApp.type == "edit") {
                                url = "/backstage/userManage/updateUser";
                                datas.id = item.id;
                                parent.vueGridApp.item = null;
                                msg = "修改";
                            }
                            var req = baseJS.ajaxRequestSsyncFalse(url,datas);
                            if (!baseJS.isEmpty(req) && req.status == 1) {
                                this.formValidate.loading = false;
                                this.formValidate.disabledReset = false;
                                parent.vueGridApp.loadedData(parent.vueGridApp.currentPage, parent.vueGridApp.pageSize);
                                baseJS.layerMsg(msg+"成功！", function callback() {
                                    parent.layer.close(parent.vueGridApp.iframeIndex);
                                });
                            } else {
                                baseJS.layerMsg(msg+"失败！");
                            }
                        }
                    })

                },
                handleReset : function(name){
                    this.$refs[name].resetFields();
                    const roleSelect = item.roleList;
                    this.formValidate.roleSelect = [];
                    for(var index in roleSelect){
                        this.formValidate.roleSelect.push(roleSelect[index].roleId);
                    }
                }
            }
        });
        formApp.$mount('#userFormApp');
    }

    var getRoleList = function () {
        var reqData = null;
        baseJS.ajaxRequest({
            url:"/role/getRoleList",
            success:function success(data) {
                reqData = data.data;
            },
            error:function error() {
                baseJS.layerMsg("获取角色失败");
            }
        });
        return reqData;
    }

    return {
        initGrid: initGrid,
        initAddForm:initAddForm
    }
})();

